package log

import (
	"context"
	"fmt"
	"gitee.com/z930255076/go-ext/utils"
	"gorm.io/gorm/logger"
	"io"
	"log"
	"os"
	"strconv"
	"strings"
	"time"
)

type SqlLogger struct {
	File     io.Writer
	LogLevel string
}

// LogMode log mode
func (l *SqlLogger) LogMode(level logger.LogLevel) logger.Interface {
	return l
}

func NewSqlLogger(logLevel string) *SqlLogger {
	file := NewFile("sql")

	return &SqlLogger{File: file, LogLevel: logLevel}
}

// Trace 实现 Trace 方法（记录 SQL）
func (l *SqlLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {
	needLog := false
	if strings.Contains(l.LogLevel, "info") {
		needLog = true
	}

	if strings.Contains(l.LogLevel, "slow") {
		slowTime, _ := strconv.Atoi(os.Getenv("SQL_SLOW_TIME"))
		if slowTime <= 0 {
			slowTime = 2
		}

		if int(time.Since(begin).Seconds()) >= slowTime {
			needLog = true
		}
	}

	sql, _ := fc()
	sqlStr := fmt.Sprintf("execute %s %s;", time.Since(begin), sql)
	if needLog {
		l.File.Write([]byte("[ SQL ] " + sqlStr + "\n"))
	}

	if os.Getenv("DEBUG") == "true" {
		utils.TE.SetAnSql(sqlStr)
	}
}

// Info 其他方法按需实现（可留空或简单处理）
func (l *SqlLogger) Info(ctx context.Context, msg string, data ...interface{}) {
	log.New(l.File, "[INFO] ", log.LstdFlags).Println(msg, data)
}

func (l *SqlLogger) Warn(ctx context.Context, msg string, data ...interface{}) {
	log.New(l.File, "[WARN] ", log.LstdFlags).Println(msg, data)
}

func (l *SqlLogger) Error(ctx context.Context, msg string, data ...interface{}) {
	log.New(l.File, "[ERROR] ", log.LstdFlags).Println(msg, data)
}

func (l *SqlLogger) TraceStart(ctx context.Context, begin time.Time, fc func() (string, int64)) context.Context {
	return ctx
}

func (l *SqlLogger) TraceEnd(ctx context.Context, begin time.Time, err error) {}
